import Vue from 'vue'
import VueRouter from 'vue-router'

import MyLogin from '@/components/MyLogin'

Vue.use(VueRouter)

const routes = [
  //一级路由（首页和登录）
  { path: '/', redirect: '/home' },
  { path: '/login', component: MyLogin },
  //这是动态导入：当访问这个规则的时候，才会导入，否则不导入
  {
    path: '/home',
    component: () => import('@/components/MyHome'),
    children: [
      // 首页的二级路由(path里面，不要加 / 。最终的地址会自动拼接成 /home/users)
      { path: 'users', component: () => import('@/components/menus/MyUsers') },
      {
        path: 'rights',
        component: () => import('@/components/menus/MyRights')
      },
      {
        path: 'orders',
        component: () => import('@/components/menus/MyOrders')
      },
      { path: 'goods', component: () => import('@/components/menus/MyGoods') },
      {
        path: 'settings',
        component: () => import('@/components/menus/MySettings')
      },
      // 用户详情，也展示到了 首页的内容区域，所以也是首页的二级路由
      {
        path: 'detail/:id',
        component: () => import('@/components/user/MyUserDetail')
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

//全局导航首守卫
router.beforeEach((to, from, next) => {
  //to 到哪里去  to.path 表示要访问那个地址
  //from  从哪里来
  // next()  ---表示放行  next(false) --不允许通过  next('/login') --强行跳转到/login
  if (to.path === '/login') {
    next()
  } else {
    if (localStorage.getItem('token')) {
      next()
    } else {
      next('/login')
    }
  }
})

export default router
